import axios from 'axios'
import { useUserStore } from '@/stores/modules/user'
// import { ElMessage } from 'element-plus'
import router from '@/router'
// import { useUserStore } from '@/stores/modules/user'
// import { computed } from 'vue'
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  // timeout: 1000 * 60 // 请求超时时间
})

// request拦截器

service.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    // config.headers['Authorization'] = 'Bearer ' + userStore.token
    // config.headers['Authorization'] =
    //   'Bearer ' +
    //   'eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjRkM2JkNGQ2LTgwMjktNDA0Yi1hOTNiLTUxYjVlNmZkZTUyNCJ9.Phx-UzuZFEpBya2qM7_3qaoR7K2Rd_bL8xke73J4Xy-wur6h2w6-0_85S_lvkTIw4zp_LvIHejvgqbr3MC8QnA'
    // const userStore = useUserStore()
    // const token = computed(() => {
    //   return userStore.token
    // })
    // if (token.value) {
    //   config.headers['Authorization'] = 'Bearer ' + token.value
    // }

    //   if (isCheckTimeout()) {
    //     // 登出操作
    //     userStore.Logout()
    //     ElMessage.warning('登录过期，请重新登录')
    //   }
    //   config.headers.Authorization = userStore.token

    return config
  },
  (error) => {
    console.error('error: ', error) // for debug
    Promise.reject(error)
  }
)

// respone拦截器
service.interceptors.response.use(
  (response) => {
    const userStore = useUserStore()
    const { code, msg } = response.data
  //  console.log("🐯 ~ response.data:", response.data)
    if (code === 200) {
      return response.data
    } else {
      // 业务错误
      console.log(code)
      if (code === 401) {
        userStore.token = ''
        router.push('/')
        ElMessage({
          message: '登录过期！请刷新页面',
          grouping: true,
          type: 'warning',
        })
      } else {
        // ElMessage.error(msg)
      }

      // return Promise.reject(new Error(msg))
    }
    
  },
  (error) => {
    // const userStore = useUserStore()
    // 处理 token 超时问题
    if (error.response && error.response.data && error.response.data.code === 401) {
      // token超时
      // userStore.Logout()
    }
    // ElMessage.error(error.message) // 提示错误信息
    return Promise.reject(error)
  }
)

export default service
